from ferris import BasicModel
from google.appengine.ext import ndb
from app.models.issue import Issue
from app.models import util


class Period(BasicModel):
    """
    Models each period of a particular publication frequency. For instance, for
    a monthly magazine, the periods could be January, February, etc. Periods
    should be assigned an order number for listing in chronological order, e.g.
    1 - January, 2 - February, etc.
    """
    name = ndb.StringProperty(required=True)
    order = ndb.IntegerProperty(required=True, default=0)
    publication_frequency = ndb.KeyProperty(kind="PublicationFrequency",
                                            required=True)

    def _post_put_hook(self, future):
        """
        Post put hook to force an update on each issue associated with this
        period to make sure computed fields are kept up-to-date.
        """
        key = future.get_result()
        if key:
            query = Issue.query(Issue.period == key)
            query.map(util.update_entity_async)
